package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.domian.vo.ChartXData;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.chart.web.controller.chart.sta.JsonsUtil.updateLegendDataNames;


/**
 * 3D散点图
 *
 * @author chart
 */
@RestController
@RequestMapping("/scatter3D/chart")
public class Scatter3DChartController extends BaseController
{


    @Autowired
    private IChartConfigsService chartConfigsService;



    //三维散点图和散点矩阵图结合
    @PostMapping("/scatterPlotsWithPolyhedron/importData")
    public AjaxResult importData(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> axleName = getdata.get(0);

            List<List<String>> dataList = new ArrayList<>();
            for (int i = 1; i < getdata.size(); i++) {
                List<String> rowData = getdata.get(i);
                if (!ObjectUtils.isEmpty(rowData)) {
                    List<String> singleData = new ArrayList<>();
                    for (int i1 = 1; i1 < rowData.size(); i1++) {
                        singleData.add(rowData.get(i1));
                    }
                    dataList.add(singleData);
                }
            }
            dataList.add(0, axleName);
            ChartXData xData = new ChartXData();
            xData.setSource(dataList);


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());


            jsonObject.put("dataset", xData);
            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }


    //三维散点图和散点矩阵图结合
    @PostMapping("/scatterPlotsWithPolyhedron/v2/importData")
    public AjaxResult v2importData(@RequestBody List<Map<String, Object>> dataLists, Long configId) throws Exception {
        //XSSFWorkbook workbook = null;
        try {
       /*     workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> axleName = getdata.get(0);

            List<List<String>> dataList = new ArrayList<>();
            for (int i = 1; i < getdata.size(); i++) {
                List<String> rowData = getdata.get(i);
                if (!ObjectUtils.isEmpty(rowData)) {
                    List<String> singleData = new ArrayList<>();
                    for (int i1 = 1; i1 < rowData.size(); i1++) {
                        singleData.add(rowData.get(i1));
                    }
                    dataList.add(singleData);
                }
            }
            dataList.add(0, axleName);
            ChartXData xData = new ChartXData();
            xData.setSource(dataList);


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());


            jsonObject.put("dataset", xData);
            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            //workbook.close();
        }
    }
    //三维散点图
    @PostMapping("/scatterPlots/v2/importData")
    public AjaxResult v2scatterPlots(@RequestBody List<Map<String, Object>> dataLists
            ,Long configId) throws Exception {
   //     XSSFWorkbook workbook = null;
        try {
      /*      workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/
            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }
            List<String> axleName =new ArrayList<>();
            List<String> sss = getdata.get(0);
            for (int i = 1; i < sss.size(); i++) {
                String s = sss.get(i);
                if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                    axleName.add(s);
                }
            }

            List<List<List<String>>> newList = new ArrayList<>();

            List<List<String>> list = new ArrayList<>();

            List<String> groupName = new ArrayList<>();

            for (int i = 1; i < getdata.size(); i++) {
                List<String> rowData = getdata.get(i);
                if (!CollectionUtils.isEmpty(rowData)) {
                    List<String> singleData = new ArrayList<>();
                    for (int i1 = 0; i1 < rowData.size(); i1++) {
                        String s = rowData.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            singleData.add(s);
                        }
                    }

                    if (i == getdata.size() - 1) {
                        list.add(singleData);
                        newList.add(list);
                    } else if (i == 1) {
                        groupName.add(singleData.get(0));
                    } else {
                        if (getdata.get(i).size() == 1) {
                            groupName.add(singleData.get(0));
                            newList.add(list);
                            list = new ArrayList<>();
                        } else {
                            list.add(singleData);
                        }
                    }
                }
            }


            ArrayList<Map> maps = new ArrayList<>();
            for (int i = 0; i < newList.size(); i++) {
                Map map = new HashMap<>();
                List<List<String>> lists = newList.get(i);

                List<List<String>> datas = new ArrayList<>();
                ArrayList<String> strings = new ArrayList<>();
                strings.add("x"+String.valueOf(i));
                strings.add("y"+String.valueOf(i));
                strings.add("z"+String.valueOf(i));
                datas.add(strings);
                    for (int i1 = 0; i1 < lists.size(); i1++) {
                        List<String> list1 = lists.get(i1);
                        String y = list1.get(0);
                        for (int i2 = 1; i2 < list1.size(); i2++) {
                            String x = axleName.get(i2-1);
                            List<String> ss = new ArrayList<>();
                            ss.add(x);
                            ss.add(y);
                            ss.add(list1.get(i2));
                            datas.add(ss);
                        }
                    }
                    map.put("source",datas);
                    maps.add(map);
            }



            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            jsonObject.put("dataset", maps);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);

            ArrayList<JSONObject> seriesList = new ArrayList<>();
            ArrayList<Map> maps1 = new ArrayList<>();
            for (int i = 0; i < groupName.size(); i++) {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.putAll(jsonObject1);

                JSONObject encode = (JSONObject) jsonObject2.get("encode");
                encode.put("x","x"+String.valueOf(i));
                encode.put("y","y"+String.valueOf(i));
                encode.put("z","z"+String.valueOf(i));

                jsonObject2.put("encode",encode);
                jsonObject2.put("name",groupName.get(i));
                seriesList.add(jsonObject2);

                Map map = new HashMap<>();
                map.put("name",groupName.get(i));
                maps1.add(map);
            }

            jsonObject.put("series", seriesList);
            JSONObject legend = (JSONObject) jsonObject.get("legend");
            legend.put("data",maps1);

            jsonObject.put("legend", legend);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
     //       workbook.close();
        }
    }


   /* 好用的 @PostMapping("/scatterPlots/importData")
    public AjaxResult scatterPlots(@RequestBody ChartDateTto chartDateTto) throws Exception {
        Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(chartDateTto.getDataList());
        List<List<String>> getdata = ExcelDataUtils.getData(sheet);

        if (CollectionUtils.isEmpty(getdata)) {
            return AjaxResult.error("请填充数据");
        }

        List<String> axleName = new ArrayList<>();
        List<String> sss = getdata.get(0);
        for (int i = 1; i < sss.size(); i++) {
            String s = sss.get(i);
            if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                axleName.add(s);
            }
        }

        List<List<List<String>>> newList = new ArrayList<>();
        List<List<String>> list = new ArrayList<>();
        List<String> groupName = new ArrayList<>();

        for (int i = 1; i < getdata.size(); i++) {
            List<String> rowData = getdata.get(i);
            if (!CollectionUtils.isEmpty(rowData)) {
                List<String> singleData = new ArrayList<>();
                for (int i1 = 0; i1 < rowData.size(); i1++) {
                    String s = rowData.get(i1);
                    if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                        singleData.add(s);
                    }
                }

                if (i == getdata.size() - 1) {
                    list.add(singleData);
                    newList.add(list);
                } else if (i == 1) {
                    groupName.add(singleData.get(0));
                } else {
                    if (getdata.get(i).size() == 1) {
                        groupName.add(singleData.get(0));
                        newList.add(list);
                        list = new ArrayList<>();
                    } else {
                        list.add(singleData);
                    }
                }
            }
        }

        ArrayList<Map> maps = new ArrayList<>();
        for (int i = 0; i < newList.size(); i++) {
            Map map = new HashMap<>();
            List<List<String>> lists = newList.get(i);

            List<List<String>> datas = new ArrayList<>();
            ArrayList<String> strings = new ArrayList<>();
            strings.add("x" + String.valueOf(i));
            strings.add("y" + String.valueOf(i));
            strings.add("z" + String.valueOf(i));
            datas.add(strings);
            for (int i1 = 0; i1 < lists.size(); i1++) {
                List<String> list1 = lists.get(i1);
                String y = list1.get(0);
                for (int i2 = 1; i2 < list1.size(); i2++) {
                    String x = axleName.get(i2 - 1);
                    List<String> ss = new ArrayList<>();
                    ss.add(x);
                    ss.add(y);
                    ss.add(list1.get(i2));
                    datas.add(ss);
                }
            }
            map.put("source", datas);
            maps.add(map);
        }

        JSONObject jsonObject = JSON.parseObject(chartDateTto.getChartValue());
        jsonObject.put("dataset", maps);

        List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
        JSONObject jsonObject1 = series.get(0);

        ArrayList<JSONObject> seriesList = new ArrayList<>();
        ArrayList<Map> maps1 = new ArrayList<>();
        for (int i = 0; i < groupName.size(); i++) {
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.putAll(jsonObject1);

            JSONObject encode = (JSONObject) jsonObject2.get("encode");
            encode.put("x", "x" + String.valueOf(i));
            encode.put("y", "y" + String.valueOf(i));
            encode.put("z", "z" + String.valueOf(i));

            jsonObject2.put("encode", encode);
            jsonObject2.put("name", groupName.get(i));
            seriesList.add(jsonObject2);

            Map map = new HashMap<>();
            map.put("name", groupName.get(i));
            maps1.add(map);
        }

        jsonObject.put("series", seriesList);

        // Fix the type casting issue here
        JSONObject legend = jsonObject.getJSONObject("legend"); // Use getJSONObject instead of get
        if (legend == null) { // Check if legend is null and initialize if necessary
            legend = new JSONObject();
        }
        legend.put("data", maps1);

        jsonObject.put("legend", legend);




        ArrayList<ChartSmartVo> newLists = new ArrayList<>();
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigValue(JSON.toJSONString(jsonObject));
        newLists.add(chartSmartVo);
        return AjaxResult.success(newLists);

    }*/




    private List<List<String>> extractDataFromListNullString(List<Map<String, Object>> dataList) {
        List<List<String>> extractedData = new ArrayList<>();

        for (Map<String, Object> row : dataList) {
            List<String> rowData = new ArrayList<>();
            for (Map.Entry<String, Object> entry : row.entrySet()) {
                Object value = entry.getValue();
                // 检查值是否为 null 或空字符串，并进行处理
                if (value == null || value.toString().isEmpty()) {
                    rowData.add("0"); // 为空或 null 时添加默认值 "0"
                } else {
                    rowData.add(value.toString());
                }
            }
            extractedData.add(rowData);
        }
        return extractedData;
    }


    @PostMapping("/scatterPlots/importData")
    public AjaxResult scatterPlots(@RequestBody ChartDateTto chartDateTto) throws Exception {
        String chartValue = chartDateTto.getChartValue();
        Integer configId = chartDateTto.getConfigId();
        List<List<String>> getdata = extractDataFromListNullString(chartDateTto.getDataList());

        // 获取seriesName列表
        ArrayList<String> seriesName = new ArrayList<>();
        for (List<String> getdatum : getdata) {
            String first = getdatum.get(0);
            seriesName.add(first);
        }
        seriesName.remove(0);

        // 更新series
        ObjectNode updatedJson = JsonsUtil.updateSeriesInJson(chartValue, seriesName);
        // 更新 legend 中 data 数组的 name 字段
        updateLegendDataNames(updatedJson, seriesName);
        // 生成并更新 dataset
        ArrayNode datasetArray = JsonsUtil.generateDataset(getdata);
        updatedJson.set("dataset", datasetArray);

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigValue(JSON.toJSONString(updatedJson));
        newList.add(chartSmartVo);

        System.out.println(JSON.toJSONString(updatedJson));
        return AjaxResult.success(newList);



    }




/*    //三维散点图
    @PostMapping("/scatterPlots/importData")
    public AjaxResult scatterPlots(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }
            List<String> axleName =new ArrayList<>();
            List<String> sss = getdata.get(0);
            for (int i = 1; i < sss.size(); i++) {
                String s = sss.get(i);
                if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                    axleName.add(s);
                }
            }

            List<List<List<String>>> newList = new ArrayList<>();

            List<List<String>> list = new ArrayList<>();

            List<String> groupName = new ArrayList<>();

            for (int i = 1; i < getdata.size(); i++) {
                List<String> rowData = getdata.get(i);
                if (!CollectionUtils.isEmpty(rowData)) {
                    List<String> singleData = new ArrayList<>();
                    for (int i1 = 0; i1 < rowData.size(); i1++) {
                        String s = rowData.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            singleData.add(s);
                        }
                    }

                    if (i == getdata.size() - 1) {
                        list.add(singleData);
                        newList.add(list);
                    } else if (i == 1) {
                        groupName.add(singleData.get(0));
                    } else {
                        if (getdata.get(i).size() == 1) {
                            groupName.add(singleData.get(0));
                            newList.add(list);
                            list = new ArrayList<>();
                        } else {
                            list.add(singleData);
                        }
                    }
                }
            }


            ArrayList<Map> maps = new ArrayList<>();
            for (int i = 0; i < newList.size(); i++) {
                Map map = new HashMap<>();
                List<List<String>> lists = newList.get(i);

                List<List<String>> datas = new ArrayList<>();
                ArrayList<String> strings = new ArrayList<>();
                strings.add("x"+String.valueOf(i));
                strings.add("y"+String.valueOf(i));
                strings.add("z"+String.valueOf(i));
                datas.add(strings);
                for (int i1 = 0; i1 < lists.size(); i1++) {
                    List<String> list1 = lists.get(i1);
                    String y = list1.get(0);
                    for (int i2 = 1; i2 < list1.size(); i2++) {
                        String x = axleName.get(i2-1);
                        List<String> ss = new ArrayList<>();
                        ss.add(x);
                        ss.add(y);
                        ss.add(list1.get(i2));
                        datas.add(ss);
                    }
                }
                map.put("source",datas);
                maps.add(map);
            }



            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            jsonObject.put("dataset", maps);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);

            ArrayList<JSONObject> seriesList = new ArrayList<>();
            ArrayList<Map> maps1 = new ArrayList<>();
            for (int i = 0; i < groupName.size(); i++) {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.putAll(jsonObject1);

                JSONObject encode = (JSONObject) jsonObject2.get("encode");
                encode.put("x","x"+String.valueOf(i));
                encode.put("y","y"+String.valueOf(i));
                encode.put("z","z"+String.valueOf(i));

                jsonObject2.put("encode",encode);
                jsonObject2.put("name",groupName.get(i));
                seriesList.add(jsonObject2);

                Map map = new HashMap<>();
                map.put("name",groupName.get(i));
                maps1.add(map);
            }

            jsonObject.put("series", seriesList);
            JSONObject legend = (JSONObject) jsonObject.get("legend");
            legend.put("data",maps1);

            jsonObject.put("legend", legend);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }*/
}
